import { Component, Input, OnInit } from '@angular/core';
import {
  UntypedFormBuilder,
  UntypedFormGroup,
  Validators,
} from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { RESPONSE_CODE } from 'src/app/share/const/base.const';
import { RESPONSE_DATA } from 'src/app/share/const/interfaces';
import { ScenarioService } from 'src/app/share/service/scenario.service';
import { DataService } from '../../feature.dataservice';
import { TScenario } from 'src/app/pages/types';

@Component({
  selector: 'app-create-scenario',
  templateUrl: './create.scenario.component.html',
  // styleUrls: [''],
})
export class CreateScenarioComponent implements OnInit {
  @Input() featureId: number = -1;

  isAddVisible = false;
  title = '创建 Scenario';
  // 新增form
  addForm!: UntypedFormGroup;

  constructor(
    private fb: UntypedFormBuilder,
    private service: ScenarioService,
    private message: NzMessageService,
    private store: DataService
  ) {}

  ngOnInit(): void {
    this.initAddForm();
    this.store.showEdit.subscribe((sid) => {
      this.showEditModal(sid);
    });
  }

  // 展示编辑弹框
  showEditModal(sid: number) {
    // console.log('sid-43--', sid);
    if (sid < 0) {
      return;
    }
    this.title = '编辑Scenario';
    // 调用接口查询数据,
    // 然后把数据放到form表单中
    this.service.getScenarioById(sid).subscribe((res) => {
      const { code, data } = res as RESPONSE_DATA<TScenario>;
      if (code == RESPONSE_CODE.SUCCESS) {
        this.addForm = this.fb.group({
          id: [data.id],
          scenario: [data.scenario, Validators.required],
          description: [data.description, Validators.required],
          // 是否是前置操作
          beforeAction: [data.beforeAction],
        });
        this.isAddVisible = true;
      }
    });
  }

  // 显示新增弹窗
  showAddModal() {
    this.title = '创建 Scenario';
    this.initAddForm();
    this.isAddVisible = true;
  }

  /**
   * 初始化添加表单
   */
  initAddForm() {
    this.addForm = this.fb.group({
      id: [null],
      scenario: [null, Validators.required],
      description: [null, Validators.required],
      // 是否是前置操作
      beforeAction: [null],
    });
  }

  handleCancel() {
    this.isAddVisible = false;
  }

  handleAddOk() {
    // 先触发手动验证
    Object.values(this.addForm.controls).forEach((control) => {
      if (control.invalid) {
        control.markAsDirty();
        control.updateValueAndValidity({ onlySelf: true });
      }
    });

    if (this.addForm.valid) {
      const value = this.addForm.value;
      const { id, scenario, description, beforeAction } = value;
      if (value.id) {
        // 修改操作
        this.service
          .updateScenario(id, {
            scenario,
            description,
            beforeAction,
          })
          .subscribe((updateRes) => {
            const { code } = updateRes as RESPONSE_DATA;
            if (code == RESPONSE_CODE.SUCCESS) {
              this.message.success('修改成功');
              this.isAddVisible = false;
              // this.addComplete.emit(id);
            }
          });
      } else {
        // 新增操作
        const payload = {
          scenario,
          description,
          beforeAction,
          fid: this.featureId,
        };
        this.service.postScenario(payload).subscribe((res) => {
          const { code, msg, data } = res as RESPONSE_DATA;
          if (code == RESPONSE_CODE.SUCCESS) {
            // console.log('data---', data);
            // 创建成功后,把Scenario id返回给父组件, 用于创建关联关系
            this.message.success('创建成功');
            this.isAddVisible = false;
            // 创建成功后, 触发接口, 重新查询数据
            this.store.featureRefresh.next(true);
          } else {
            this.message.error(msg);
          }
        });
      }
      console.log('value----', value);
    }
  }
}
